﻿// DateString
// ----------
ko.bindingHandlers.dateTimeString = {
    update: function(element, valueAccessor, allBindingsAccessor, viewModel) {
        var value = valueAccessor();

        var valueUnwrapped = ko.utils.unwrapObservable(value);
        if (!(valueUnwrapped instanceof Date))
            valueUnwrapped = new Date(Date.parse(valueUnwrapped));

        var timeObj = {
            hour: valueUnwrapped.getHours(),
            minute: valueUnwrapped.getMinutes()
            //second: valueUnwrapped.g
        };
        $(element).text(
            $.datepicker.formatDate('yy/mm/dd', valueUnwrapped) +
            ' ' +
            $.datepicker.formatTime('hh:mm tt', timeObj));
    }
};

// DateTimePicker
// -------------
ko.bindingHandlers.datetimepickerHandler = {
    updating: false,

    init: function (element, valueAccessor, allBindingsAccessor) {
        
        // init datetimepicker
        var options = allBindingsAccessor().datetimepickerOptions || {};
        $(element).datetimepicker(options);

        // handle the control changing
        ko.utils.registerEventHandler(element, 'change', function () {
            if (updating)
                return;
            
            var value = $(element).datetimepicker('getDate');
            var observable = valueAccessor();
            observable(value);
        });

        // handle disposal (KO removes the template binding)
        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
            $(element).datetimepicker('destroy');
        });
    },

    update: function (element, valueAccessor) {
        updating = true;
        
        // get viewmodel value
        var value = ko.utils.unwrapObservable(valueAccessor());

        // get datetimepicker value
        var current = $(element).datetimepicker('getDate');
        
        // set the date from the viewmodel if changed
        if (value - current !== 0) {
            var valueFromViewModel = new Date(Date.parse(value));
            $(element).datetimepicker('setDate', valueFromViewModel);
        };

        updating = false;
    }
};